package com.cgq.pro.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.cgq.base.dao.impl.BaseDaoImpl;
import com.cgq.pro.dao.UserDao;
import com.cgq.pro.entity.User;

/**
 * 数据访问组件
 * 用户管理
 * @author chenkaile
 *
 */
@Repository
public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {

	@SuppressWarnings("rawtypes")
	public User findUserByNameAndPwd(User user) {
		String hql="from User o where o.name='"+user.getName()+"' and o.password='"+user.getPassword()+"'";
		List list=new ArrayList();
		list=hibernateTemplate.find(hql);
		if(list.size()>0)
			return (User) list.get(0);
		else
			return null;
	}

	public List<User> getAllRecords(final int start,final int pageSize,
			Map<String, String> map) {
		final StringBuilder hql=new StringBuilder();
		hql.append("from User o ");
		if(map!=null && map.size()>0){
			//可以扩展实现搜索功能
		}
		List list=null;
		try {
			list=hibernateTemplate.executeFind(new HibernateCallback() {

				public List doInHibernate(Session session)
						throws HibernateException, SQLException {
					Query query = session.createQuery(hql.toString()); 
					query.setFirstResult(start);
					query.setMaxResults(pageSize);
					return query.list();
				}
			});
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		return list;
	}

	public int getTotal(Map<String, String> map) {
		final StringBuilder hql=new StringBuilder();
		hql.append("from User o ");
		if(map!=null && map.size()>0){
			
		}
		List list=hibernateTemplate.find(hql.toString());
		if(list!=null && list.size()>0)
			return list.size();
		else 
			return 0;
	}
}
